package com.example.easyexcel.util;

import cn.hutool.core.io.resource.ClassPathResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.IOException;
import java.io.InputStream;

/**
 * 文件读取工具类
 *
 * @author tu228
 */
public class FileReadUtil {

    private static final Logger log = LoggerFactory.getLogger(FileReadUtil.class);

    /**
     * 获取resouce文件
     *    注意：须通过mvn clean install将文件打包到classes目录下,才能读取到
     *    例如本项目classes目录：E:\office\study\study_base\01.file\easyExcel\code\easyexcel-demo\target\classes\templates
     *
     * @param filePath 文件路径
     *      如：String filePath = "excelTemplate/report/rptPasExpenseDetail.xlsx";
     * @return
     * @throws RuntimeException 运行时异常
     */
    public static InputStream getResourceFile(String filePath) throws RuntimeException {
        // 获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try{
            Resource[] resources = resolver.getResources(filePath);
            if (resources.length <= 0){
                throw new RuntimeException("未找到文件[" + filePath + "]");
            }
            InputStream inputStream = resources[0].getInputStream();
            return inputStream;
        }catch (IOException e){
            if (log.isWarnEnabled()){
                log.warn("读取文件流失败" + e);
            }

            throw new RuntimeException("读取文件流失败");
        }finally {

        }
    }

    /**
     * 根据相对路径，获取到文件绝对路径
     *    注意：须通过mvn clean install将文件打包到classes目录下,才能读取到
     *    例如本项目classes目录：E:\office\study\study_base\01.file\easyExcel\code\easyexcel-demo\target\classes\templates
     *
     * @param filePath 相对路径
     * @return
     * @throws RuntimeException 运行时异常
     */
    public static String getClassesFilePath(String filePath) throws RuntimeException {
        final ClassPathResource classPathResource = new ClassPathResource(filePath);
        return classPathResource.getAbsolutePath();
    }
}
